package com.equipment.management.util;

import com.equipment.management.entity.Mainframe;
import com.equipment.management.mqtt.MqttGateway;
import com.equipment.management.service.TaskService;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/*
 * @version 1.0 created by Carol on 2018/8/27 9:25
 */
@Component
public class Schedultask extends Base64Util implements SchedulingConfigurer {
    private static final Logger LOGGER = LoggerFactory.getLogger(Schedultask.class);

    @Autowired
    private TaskService taskService;
    @Autowired
    private MqttGateway mqttGateway;
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        try {
            taskService.queryScheduledTask().forEach((cron)->{
                scheduledTaskRegistrar.addTriggerTask(
                        //1.添加任务内容(Runnable)，可以为方法
                        () -> {
                            try {
                                scan(cron);
                            } catch (MqttException e) {
                                e.printStackTrace();
                            }
                        },
                        //2.设置执行周期(Trigger)
                        triggerContext -> {
                            //2.1 从数据库获取执行周期，在这里调用不同的方法返回不同的定时任务信息
                            System.out.println(cron);
                            //2.2 合法性校验.
                            if (StringUtils.isEmpty(cron)) {
                                // Omitted Code ..
                                LOGGER.error("计划任务为空");
                                return  null;
                            }
                            //2.3 返回执行周期(Date)
                            return new CronTrigger(cron.getType()).nextExecutionTime(triggerContext);
                        }
                );
            });

        }catch (Exception e){
            LOGGER.info(e.toString());
        }
    }






    public void scan(Mainframe cron) throws MqttException {
        String random=random();
        mqttGateway.sendToMqtt("scan"+"#"+cron.getPayload(), "device_sub:"+cron.getCode());
        mqttGateway.sendToMqtt("scan"+"#"+cron.getPayload(), "device_pub:"+cron.getCode());
        String code1="device_sub:"+cron.getCode();
        String code2="device_pub:"+cron.getCode();
        subscribe(code1,cron.getOperate(), random);
        subscribe(code2,cron.getOperate(), random);


    }





}